/*
 * Functions that are needed to create the map.  You must declare a
 * variable called MARKERS before.  This exports the function
 * 'onLoad()' to be used as the onload event of the page to create the
 * map.
 */

var map;

// These are set by the php file
var avgLat = 0;
var avgLng = 0;

var ZOOM_VALUE = 15;
var REALLY_ZOOM_VALUE = 19;

// Keep around to focus on the last marker
var lastMarker;
var lastPopupFunction;

function onLoad(name) {
  var m = document.getElementById("map");
  if (!m) {
    alert("You must defined an HTML element named 'map'");
    return;
  }

  map = new GMap2(m);
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  
  var lat = avgLat;
  var lng = avgLng;
  var scale = 11;
  // XXX: Complete fucking hack, but I ahve to run in a second... will fix later
  try {
    lat += LAT_NUDGE;
  } catch (e) {}
  try {
    lng += LNG_NUDGE;
  } catch (e) {}
  try {
    lat = LAT;
  } catch (e) {}
  try {
    lng = LNG;
  } catch (e) {}
  try {
    scale = SCALE;
  } catch (e) {}
  map.setCenter(new GLatLng(lat,lng),scale);

  createMarkers();

  // If we've specified just one, focus on it
  if (name) {
    map.setCenter(lastMarker.getLatLng());    
    lastPopupFunction(); // ghettooooooooooooooooooo!!!!
  }
}

function number2month(i) {
  if (i== 1) return "Jan";
  if (i== 2) return "Feb";
  if (i== 3) return "Mar";
  if (i== 4) return "Apr";
  if (i== 5) return "May";
  if (i== 6) return "Jun";
  if (i== 7) return "Jul";
  if (i== 8) return "Aug";
  if (i== 9) return "Sep";
  if (i==10) return "Oct";
  if (i==11) return "Nov";
  if (i==12) return "Dec";
}

/** 
 * This sucks, I should die for writing this.  Especially since I've
 * written it in PHP, too
 */
function formatDate(dt) {
  //
  // 20060226062615
  //
  var year      = dt.substr( 0, 4);
  var month     = dt.substr( 4, 2);
  var day       = dt.substr( 6, 2);
  var hour      = dt.substr( 8, 2);
  var minutes   = dt.substr(10, 2);
  var seconds   = dt.substr(12, 2);
  var monthString = number2month(month);
  var d = day; //parseInt(day);
  var h = hour; //parseInt(hour);
  var m = minutes;
  var s = seconds; //parseInt(seconds);
  h = h + 3; // don't know why? 
  if (h>24) h -= 24;
  var amPm;
  if (h > 12) {
    h -= 12;
    amPm = "pm";
  } else {
    if (h >= 12) h -= 12; //??? wtf
    amPm = "am";
  }

  return monthString + " " + d + ", " + year; // + " @ " + h + ":" + m + " " + amPm;
}

function createMarker(name,description,location,lat,lng) {
  //
  // Some points may be off, so you can define a global nudge to move them
  //
  try {
    lat += LAT_NUDGE;
  } catch (e) {}
  try {
    lng += LNG_NUDGE;
  } catch (e) {}
  var point = new GLatLng(lat,lng); //XXX Hack
  var marker = new GMarker(point);
  map.addOverlay(marker);
  GEvent.addListener(marker, 'click', lastPopupFunction = newPopup(name,marker,description,location));
  GEvent.addListener(marker, 'mouseover', newHoverPopup(name,marker,description,location,lat,lng));
  GEvent.addListener(marker, 'mouseout', function(e) {closeHoverPopup(marker);});
  lastMarker = marker;
}

function closeHoverPopup(marker) {
  marker.closeInfoWindow();
}

function popupBottom(lat,lng,location) {
  var s = '';
  s += '<div class="mapPopupBottom">';
  s +=           googleDirectionsHref(lat,lng,location);
  s += " | "   + zoomHref(lat,lng,ZOOM_VALUE);
  s += " | "   + zoomHref(lat,lng,REALLY_ZOOM_VALUE);
  s += '</div>';  
  return s;
}

function newHoverPopup(name,marker,description,location,lat,lng) {
  var content = html("<span class='popuptitle'>" 
                     + description + "</span><br/>" 
                     + br(1)
                     + "<span class='coords'>(" + lat + "," + lng + ")</span>"
                     + br(1)
                     + popupBottom(lat,lng,location),
                     true /*no min height*/);
  var _marker = marker;
  return function() {
    _marker.openInfoWindowHtml(content);
  };
}

function newPopup(name,marker,description,location) {
  var content = createPopupContent(name,marker,description,location);
  var _marker = marker;
  return function() {
    _marker.openInfoWindowHtml(content);
  };
}

function createPopupContent(name,marker,description,location) {
  var content = '<div class="contentWrapper">';
  content    += '<div class="contentItem">';
  content    += '<img src="' + name + '.jpg"></img>';
  content    += '</div>';
  content    += '<div class="contentItem">';
  content    += br();
  content    += wrapTitle(location);
  content    += br();
  content    += description;
  content    += br();
  content    += em(formatDate(name));
  content    += br();
  content    += '</div>';
  content    += '</div>'


  return html(content);
}

/**
 * @param noMinHeight true for no min-height attribute in the style
 */
function html(txt,noMinHeight) {
	return htmlStart(noMinHeight) + txt + htmlEnd();
}

function htmlStart(noMinHeight) {
	var s = "<div id='mainInfoDiv' style='";
  if (!noMinHeight) {
    s += "min-height:200px; ";
  }
  s += "text-align:left; padding: 2px; ' >";
	return s;
}

function htmlEnd() {
	return "</div>";
}

/**
 * Wraps the title in <b> tags.
 */
function wrapTitle(s) {
  return '<b>' + s + '</b>';
}

/**
 * Returns n number of <br/> tags.
 */
function br(n) {
  if (!n || n<1) n=1;
  var s = '';
  for (var i=0; i<n; i++) s += '<br/>';
  return s;
}

/**
 * Wraps in <em> tags.
 */
function em(s) {
  return '<em>' + s + '</em>';
}

function googleDirectionsHref(lat,lng,location) {
  return "<a href='" + createGoogleDirectionsLink(lng,lng,location) + "'>Directions</a>";
}

function createGoogleDirectionsLink(lat,lng,location) {
  var url = 'http://maps.google.com/maps';
  url += '?dq=' + escape(removeHTML(location));
  url += '&daddr=' + escape(removeHTML(location));
  url += '&geocode=3151963666485444653,' + lat + ',' + lng;
  url += '&oi=local_result&resnum=1&ct=directions-to';
  return url;
}

function zoomLink(lat,lng,amount) {
  return "map.setCenter(new GLatLng(" + lat + ", " + lng + "), " + amount + ")";
}

function zoomHref(lat,lng,amount) {
  var res = "<a href='#' onclick='" + zoomLink(lat,lng,amount) + "'>";
  if (amount == REALLY_ZOOM_VALUE) {
    res += "<b>";
  }
  res += "Zoom";
  if (amount == REALLY_ZOOM_VALUE) {
    res += "!</b>";
  }
  res += "</a>";
  return res;
}

function removeHTML(s){
  if (!s) return s;
  s = s.replace(/&(lt|gt);/g, function (strMatch, p1){
 		 	return (p1 == "lt")? "<" : ">";
 		});
  return s.replace(/<\/?[^>]+(>|$)/g, "");
}    

